﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;

namespace System.Controls.Converters
{
  public class Thickness2GridLengthConverter : IValueConverter
  {
    private static bool TryGetValue( string position, double value, out double thick )
    {
      thick = value;
      var iValue = 0;

      if ( position == "1" )
      {
        thick = value;
        return true;
      }

      if ( position.StartsWith( "+" ) )
      {
        position = position.Remove( 0, 1 );
        if ( int.TryParse( position, out iValue ) )
        {
          thick = value + iValue;
          return true;
        }
      }

      if ( position.StartsWith( "*" ) )
      {
        position = position.Remove( 0, 1 );
        if ( int.TryParse( position, out iValue ) )
        {
          thick = value * iValue;
          return true;
        }
      }

      if ( !position.StartsWith( "/" ) )
        return false;

      position = position.Remove( 0, 1 );
      if ( !int.TryParse( position, out iValue ) || iValue <= 0 )
        return false;

      thick = value / iValue;
      return true;
    }

    #region Implementation of IValueConverter

    public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
    {
      if ( !( value is Thickness ) || parameter == null )
        return value;

      var thickness = (Thickness) value;
      var positions = parameter.ToString().Split( new[]
                                                  {
                                                    ','
                                                  }, StringSplitOptions.RemoveEmptyEntries );
      var index = 0;
      foreach ( var position in positions )
      {
        var thick = 0.0;
        if ( index == 0 && TryGetValue( position, thickness.Left, out thick ) )
          return new GridLength( thick, GridUnitType.Pixel );

        if ( index == 1 && TryGetValue( position, thickness.Top, out thick ) )
          return new GridLength( thick, GridUnitType.Pixel );

        if ( index == 2 && TryGetValue( position, thickness.Right, out thick ) )
          return new GridLength( thick, GridUnitType.Pixel );

        if ( index == 3 && TryGetValue( position, thickness.Bottom, out thick ) )
          return new GridLength( thick, GridUnitType.Pixel );

        index++;
      }

      return thickness;
    }

    public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
    {
      return null;
    }

    #endregion
  }
}
